package com.tanhua.server.service;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.Settings;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SettingsService {
    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private BlackListApi blackListApi;

    public SettingsVo settings() {
        Long userId = UserHolder.getUserId();
        String mobile = UserHolder.getMobile();
        SettingsVo vo=new SettingsVo();
        vo.setPhone(mobile);
        vo.setId(userId);

        Question question=questionApi.findByUserId(userId);
        String txt=question==null?"你喜欢java吗":question.getTxt();
        vo.setStrangerQuestion(txt);

        Settings settings = settingsApi.findByUserId(userId);
        if(settings!=null){
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setLikeNotification(settings.getLikeNotification());
        }
        return vo;
    }

    public void save(String content) {
        Long userId = UserHolder.getUserId();
        Question question = questionApi.findByUserId(userId);
        if(question==null){
            question=new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        }else {
            question.setTxt(content);
            questionApi.update(question);
        }
    }

    public PageResult page(int page, int size) {
        Long userId = UserHolder.getUserId();
        IPage<UserInfo> pageInfo=blackListApi.findByUserId(userId,page,size);
        PageResult pageResult=new PageResult(page,size,pageInfo.getTotal(),pageInfo.getRecords());

        return pageResult;
    }

    public void deleteBlacklist(Long blackUserId) {
        Long userId = UserHolder.getUserId();
        blackListApi.delete(userId,blackUserId);
    }

    //修改通知设置
    public void setting(Settings settings) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        settings.setUserId(userId);
        settings.setUpdated(new Date());
        //调用spi,查看设置是否存在
        Settings setting = settingsApi.findByUserId(userId);
        if(setting==null){
            settings.setCreated(new Date());
            settingsApi.save(settings);
        }
        settingsApi.update(settings);
    }
}
